package com.liu.io.file.pdf;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2Font;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * pdf转图片
 * https://blog.csdn.net/weixin_36380516/article/details/76984283
 */

public class PdfToImg {
	public static void toImg(String filePath, String toPath) throws IOException {
		PDDocument doc = PDDocument.load(filePath);
		PDCIDFontType2Font.msyh = Style.MSYH;
		@SuppressWarnings("unchecked")
		List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
		for (int i = 0; i < pages.size(); i++) {
			PDPage page = (PDPage) pages.get(i);
			BufferedImage image = page.convertToImage();
			Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix(("jpg"));
			ImageWriter writer = (ImageWriter) iter.next();
			String filename = toPath + filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."))
					+ ".jpg";
			File outFile = new File(filename);
			FileOutputStream out = new FileOutputStream(outFile);
			ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
			writer.setOutput(outImage);
			writer.write(new IIOImage(image, null, null));
			outImage.close();
			out.close();
		}
		doc.close();
	}

	public static void main(String[] args) {
		String filePath = "C:/Users/12961/Desktop/Velocity标签技术.pdf";
		String toPath = "C:/Users/12961/Desktop";
		try {
			toImg(filePath, toPath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
